<!-- 过程检验单的关联检测项目列表组件 -->
<template>
  <div class="test-items-container" v-if="ipqcId">
    <!-- 搜索条件 -->
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="检测项名称" prop="indexName">
        <el-input
          v-model="queryParams.indexName"
          placeholder="请输入检测项名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="检测项编码" prop="indexCode">
        <el-input
          v-model="queryParams.indexCode"
          placeholder="请输入检测项编码"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="检测项类型" prop="indexType">
        <el-select v-model="queryParams.indexType" placeholder="请选择检测项类型" clearable size="small">
          <el-option
            v-for="dict in indexTypeOptions"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    
    <!-- 操作按钮区域 -->
    <div class="table-toolbar">
      <el-button
        type="primary"
        icon="el-icon-plus"
        size="mini"
        @click="handleAddTestItem"
      >新增检测项</el-button>
      <el-button
        type="danger"
        icon="el-icon-delete"
        size="mini"
        :disabled="!selectedItems.length"
        @click="handleBatchDelete"
      >批量删除</el-button>
      <el-button
        type="warning"
        icon="el-icon-search"
        size="mini"
        @click="showSearch = !showSearch"
      >{{ showSearch ? '隐藏搜索' : '显示搜索' }}</el-button>
    </div>
    
    <el-table
      v-loading="loading"
      :data="testItemsList"
      border
      height="400" 
      style="width: 100%"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column type="index" label="序号" width="50" align="center" />
      <el-table-column prop="indexName" label="检测项目" min-width="100" :show-overflow-tooltip="true" />
      <el-table-column prop="indexCode" label="检测项编码" min-width="80" :show-overflow-tooltip="true" />
      <el-table-column prop="standerVal" label="标准值" width="80" align="center" />
      <el-table-column prop="checkMethod" label="检测要求" min-width="150" :show-overflow-tooltip="true" />
      <el-table-column prop="qcTool" label="检测工具" min-width="100" :show-overflow-tooltip="true" />
      <el-table-column prop="thresholdMax" label="上限" width="70" align="center" />
      <el-table-column prop="thresholdMin" label="下限" width="70" align="center" />
      <el-table-column prop="unit" label="单位" width="70" align="center" />
      <el-table-column label="检测项类型" width="100" align="center">
        <template slot-scope="scope">
          {{ formatIndexType(scope.row.indexType) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="170" align="center">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleEditTestItem(scope.row)">编辑</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleViewTestItem(scope.row)">查看</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDeleteTestItem(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 分页 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="fetchTestItems"
    />
    
    <!-- 空数据提示 -->
    <div v-if="testItemsList.length === 0 && !loading" class="empty-data">
      <el-empty description="暂无检测项目数据"></el-empty>
    </div>
    
    <!-- 检测项表单对话框 -->
    <el-dialog
      :title="testItemFormTitle"
      :visible.sync="testItemDialogVisible"
      width="700px"
      append-to-body
      :close-on-click-modal="false">
      <el-form :model="testItemForm" :rules="testItemRules" ref="testItemFormRef" label-width="100px">
        <el-form-item label="检测项ID" prop="indexId">
          <el-input 
            v-model="testItemForm.indexId" 
            placeholder="点击选择检测项" 
            readonly 
            @click.native="openTestItemSelector"
            class="input-with-select">
            <el-button slot="append" icon="el-icon-search" @click="openTestItemSelector"></el-button>
          </el-input>
        </el-form-item>
        <el-form-item label="检测项名称" prop="indexName">
          <el-input v-model="testItemForm.indexName" placeholder="请输入检测项名称" />
        </el-form-item>
        <el-form-item label="检测项编码" prop="indexCode">
          <el-input v-model="testItemForm.indexCode" placeholder="请输入检测项编码" />
        </el-form-item>
        <el-form-item label="检测项类型" prop="indexType">
          <el-select v-model="testItemForm.indexType" placeholder="请选择检测项类型" style="width: 100%">
            <el-option
              v-for="item in indexTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="标准值" prop="standerVal">
              <el-input-number v-model="testItemForm.standerVal" :precision="2" :step="0.1" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单位" prop="unit">
              <el-input v-model="testItemForm.unit" placeholder="请输入单位" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="上限" prop="thresholdMax">
              <el-input-number v-model="testItemForm.thresholdMax" :precision="2" :step="0.1" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="下限" prop="thresholdMin">
              <el-input-number v-model="testItemForm.thresholdMin" :precision="2" :step="0.1" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="检测工具" prop="qcTool">
          <el-input v-model="testItemForm.qcTool" placeholder="请输入检测工具" />
        </el-form-item>
        <el-form-item label="检测要求" prop="checkMethod">
          <el-input v-model="testItemForm.checkMethod" type="textarea" :rows="3" placeholder="请输入检测要求" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelTestItemForm">取 消</el-button>
        <el-button type="primary" @click="submitTestItemForm">确 定</el-button>
      </div>
    </el-dialog>
    
    <!-- 检测项详情对话框 -->
    <el-dialog
      title="检测项详情"
      :visible.sync="testItemDetailVisible"
      width="700px"
      append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="检测项名称">{{ testItemDetail.indexName }}</el-descriptions-item>
        <el-descriptions-item label="检测项编码">{{ testItemDetail.indexCode }}</el-descriptions-item>
        <el-descriptions-item label="检测项类型">{{ formatIndexType(testItemDetail.indexType) }}</el-descriptions-item>
        <el-descriptions-item label="标准值">{{ testItemDetail.standerVal }}</el-descriptions-item>
        <el-descriptions-item label="单位">{{ testItemDetail.unit }}</el-descriptions-item>
        <el-descriptions-item label="上限">{{ testItemDetail.thresholdMax }}</el-descriptions-item>
        <el-descriptions-item label="下限">{{ testItemDetail.thresholdMin }}</el-descriptions-item>
        <el-descriptions-item label="检测工具">{{ testItemDetail.qcTool }}</el-descriptions-item>
        <el-descriptions-item label="检测要求" :span="2">{{ testItemDetail.checkMethod }}</el-descriptions-item>
      </el-descriptions>
      <div slot="footer" class="dialog-footer">
        <el-button @click="testItemDetailVisible = false">关 闭</el-button>
      </div>
    </el-dialog>
    
    <!-- 检测项选择器对话框 -->
    <el-dialog
      title="选择检测项"
      :visible.sync="testItemSelectorVisible"
      width="800px"
      append-to-body>
      <div class="tips-box">
        <i class="el-icon-info"></i> 提示：点击表格行可直接选择检测项
      </div>
      <el-form :inline="true" :model="selectorQueryParams" class="selector-search">
        <el-form-item label="检测项名称">
          <el-input v-model="selectorQueryParams.indexName" placeholder="请输入检测项名称" clearable size="small" />
        </el-form-item>
        <el-form-item label="检测项编码">
          <el-input v-model="selectorQueryParams.indexCode" placeholder="请输入检测项编码" clearable size="small" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="searchTemplateItems">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetSelectorQuery">重置</el-button>
        </el-form-item>
      </el-form>
      
      <el-table
        v-loading="selectorLoading"
        :data="templateItemsList"
        border
        height="350"
        style="width: 100%"
        @row-click="selectTestItem">
        <el-table-column type="index" label="序号" width="50" align="center" />
        <el-table-column prop="indexId" label="检测项ID" width="70" align="center" />
        <el-table-column prop="indexName" label="检测项名称" min-width="100" :show-overflow-tooltip="true" />
        <el-table-column prop="indexCode" label="检测项编码" min-width="80" :show-overflow-tooltip="true" />
        <el-table-column prop="indexType" label="检测项类型" width="100" align="center">
          <template slot-scope="scope">
            {{ formatIndexType(scope.row.indexType) }}
          </template>
        </el-table-column>
        <el-table-column prop="standerVal" label="标准值" width="70" align="center" />
        <el-table-column prop="thresholdMax" label="上限" width="70" align="center" />
        <el-table-column prop="thresholdMin" label="下限" width="70" align="center" />
        <el-table-column prop="unit" label="单位" width="70" align="center" />
        <el-table-column prop="crQuantityNum" label="致命缺陷" width="85" align="center" />
        <el-table-column prop="majQuantityNum" label="严重缺陷" width="85" align="center" />
        <el-table-column prop="minQuantityNum" label="轻微缺陷" width="85" align="center" />
        <el-table-column label="操作" width="80" align="center">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-check"
              @click="selectTestItem(scope.row)">选择</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <pagination
        v-show="selectorTotal > 0"
        :total="selectorTotal"
        :page.sync="selectorQueryParams.pageNum"
        :limit.sync="selectorQueryParams.pageSize"
        @pagination="fetchTemplateItems"
      />
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="testItemSelectorVisible = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
  <div v-else class="empty-container">
    <!-- 不展示任何内容 -->
  </div>
</template>

<script>
import { getQcIpqcLineList, addQcIpqcLine, updateQcIpqcLine, delQcIpqcLine } from "@/api/qc/ProcesInspection";
import { selectQcTemplateIndexList } from "@/api/qc/QualitySchemeOrder"; // 修改API引用


export default {
  name: "TestItemsList",
  
  props: {
    // 过程检验单ID
    ipqcId: {
      type: [Number, String],
      default: null
    },
    // 质检方案ID (用于新建时)
    templateId: {
      type: [Number, String],
      default: null
    }
  },
  data() {
    return {
      // 检测项目数据
      testItemsList: [],
      // 加载状态
      loading: false,
      // 是否显示搜索条件
      showSearch: false,
      // 总记录数
      total: 0,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        indexName: null,
        indexCode: null,
        indexType: null
      },
      // 选中的检测项
      selectedItems: [],
      // 检测项表单对话框是否可见
      testItemDialogVisible: false,
      // 检测项表单标题
      testItemFormTitle: '',
      // 检测项表单数据
      testItemForm: {
        lineId: null,
        ipqcId: null,
        indexId: null,
        indexCode: null,
        indexName: null,
        indexType: null,
        qcTool: null,
        checkMethod: null,
        standerVal: null,
        unit: null,
        thresholdMax: null,
        thresholdMin: null,
        crQuantityNum: null,
        majQuantityNum: null,
        minQuantityNum: null,
        attr1: null,
        attr2: null,
        attr3: null,
        attr4: null
      },
      // 检测项表单校验规则
      testItemRules: {
        indexName: [
          { required: true, message: "检测项名称不能为空", trigger: "blur" }
        ],
        indexCode: [
          { required: true, message: "检测项编码不能为空", trigger: "blur" }
        ],
        indexType: [
          { required: true, message: "检测项类型不能为空", trigger: "change" }
        ]
      },
      // 检测项类型选项
      indexTypeOptions: [
        { value: '1', label: '外观' },
        { value: '2', label: '视觉' },
        { value: '3', label: '尺寸' },
        { value: '4', label: '物理性能检测' },
        { value: '5', label: '化学成分检测' }
      ],
      // 检测项详情对话框是否可见
      testItemDetailVisible: false,
      // 检测项详情数据
      testItemDetail: {},
      
      // 检测项选择器相关数据
      testItemSelectorVisible: false,
      selectorLoading: false,
      templateItemsList: [],
      selectorTotal: 0,
      selectorQueryParams: {
        pageNum: 1,
        pageSize: 10,
        indexName: null,
        indexCode: null,
        templateId: null
      }
    }
  },
  watch: {
    ipqcId: {
      handler(val) {
        if (val) {
          console.log('TestItemsList组件检测到ipqcId变化:', val);
          this.resetQuery();
        } else {
          this.testItemsList = [];
          this.total = 0;
        }
      },
      immediate: true
    }
  },
  methods: {
    // 搜索按钮操作
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.fetchTestItems();
    },
    
    // 重置按钮操作
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        indexName: null,
        indexCode: null,
        indexType: null
      };
      if (this.ipqcId) {
        this.fetchTestItems();
      }
    },
    
    // 重置表单
    resetForm(refName) {
      if (this.$refs[refName]) {
        this.$refs[refName].resetFields();
      }
    },
    
    // 获取检测项目列表
    async fetchTestItems() {
      if (!this.ipqcId) {
        console.log('TestItemsList组件: 没有过程检验单ID，无法获取检测项目');
        this.testItemsList = [];
        this.total = 0;
        return;
      }
      
      this.loading = true;
      try {
        // 确保ipqcId是数值类型
        const originalId = this.ipqcId;
        const ipqcId = parseInt(this.ipqcId, 10);
        console.log('TestItemsList组件: 查询检测项目，过程检验单ID:', ipqcId);
        
        if (isNaN(ipqcId)) {
          throw new Error('过程检验单ID必须是数字');
        }
        
        // 构建查询参数
        const queryParams = {
          ...this.queryParams,
          ipqcId: ipqcId
        };
        
        // 调用API方法获取数据
        
        const res = await getQcIpqcLineList(ipqcId, queryParams);
        if (res && res.rows) {
          this.testItemsList = res.rows;
          this.total = res.total;
          console.log('TestItemsList组件: 获取到检测项目数量:', res.rows.length, '总记录数:', res.total);
        } else {
          this.testItemsList = [];
          this.total = 0;
          console.log('TestItemsList组件: 未获取到检测项目或返回格式不正确');
        }
        
      } catch (error) {
        console.error('TestItemsList组件: 获取检测项目列表异常:', error);
        this.$message.error('获取检测项目列表失败: ' + (error.message || '未知错误'));
        this.testItemsList = [];
        this.total = 0;
      } finally {
        this.loading = false;
      }
    },
    
    // 处理表格选择变化
    handleSelectionChange(selection) {
      this.selectedItems = selection;
    },
    
    // 新增检测项
    handleAddTestItem() {
      this.testItemForm = {
        lineId: null,
        ipqcId: this.ipqcId,
        indexId: null,
        indexCode: null,
        indexName: null,
        indexType: null,
        qcTool: null,
        checkMethod: null,
        standerVal: null,
        unit: null,
        thresholdMax: null,
        thresholdMin: null,
        crQuantityNum: null,
        majQuantityNum: null,
        minQuantityNum: null,
        attr1: null,
        attr2: null,
        attr3: null,
        attr4: null
      };
      this.testItemFormTitle = '新增检测项';
      this.testItemDialogVisible = true;
      this.$nextTick(() => {
        if (this.$refs.testItemFormRef) {
          this.$refs.testItemFormRef.clearValidate();
        }
      });
    },
    
    // 编辑检测项
    handleEditTestItem(row) {
      this.testItemForm = JSON.parse(JSON.stringify(row));
      this.testItemFormTitle = '编辑检测项';
      this.testItemDialogVisible = true;
      this.$nextTick(() => {
        if (this.$refs.testItemFormRef) {
          this.$refs.testItemFormRef.clearValidate();
        }
      });
    },
    
    // 查看检测项详情
    handleViewTestItem(row) {
      this.testItemDetail = row;
      this.testItemDetailVisible = true;
    },
    
    // 删除单个检测项
    handleDeleteTestItem(row) {
      this.$confirm('确认删除该检测项吗?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteTestItem([row.lineId]);
      }).catch(() => {});
    },
    
    // 批量删除检测项
    handleBatchDelete() {
      if (this.selectedItems.length === 0) {
        this.$message.warning('请选择要删除的检测项');
        return;
      }
      
      const lineIds = this.selectedItems.map(item => item.lineId);
      this.$confirm(`确认删除选中的${lineIds.length}个检测项吗?`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteTestItem(lineIds);
      }).catch(() => {});
    },
    
    // 删除检测项
    async deleteTestItem(lineIds) {
      try {
        await delQcIpqcLine(lineIds);
        this.$message.success('删除成功');
        this.fetchTestItems();
      } catch (error) {
        console.error('删除检测项异常:', error);
        this.$message.error('删除失败: ' + (error.message || '未知错误'));
      }
    },
    
    // 取消检测项表单
    cancelTestItemForm() {
      this.testItemDialogVisible = false;
      this.testItemForm = {
        lineId: null,
        ipqcId: null,
        indexId: null,
        indexCode: null,
        indexName: null,
        indexType: null,
        qcTool: null,
        checkMethod: null,
        standerVal: null,
        unit: null,
        thresholdMax: null,
        thresholdMin: null,
        crQuantityNum: null,
        majQuantityNum: null,
        minQuantityNum: null,
        attr1: null,
        attr2: null,
        attr3: null,
        attr4: null
      };
    },
    
    // 提交检测项表单
    submitTestItemForm() {
      this.$refs.testItemFormRef.validate(async valid => {
        if (valid) {
          try {
            const formData = JSON.parse(JSON.stringify(this.testItemForm));
            formData.ipqcId = parseInt(this.ipqcId, 10);
            
            if (formData.lineId) {
              // 修改
              await updateQcIpqcLine(formData);
              this.$message.success('修改成功');
            } else {
              // 新增
              await addQcIpqcLine(formData);
              this.$message.success('新增成功');
            }
            
            this.testItemDialogVisible = false;
            this.fetchTestItems();
          } catch (error) {
            console.error('保存检测项异常:', error);
            this.$message.error('保存失败: ' + (error.message || '未知错误'));
          }
        }
      });
    },
    
    // 格式化检测项类型
    formatIndexType(type) {
      if (!type) return '';
      
      const typeMap = {
        '1': '外观',
        '2': '视觉',
        '3': '尺寸',
        '4': '物理性能检测',
        '5': '化学成分检测'
      };
      
      return typeMap[type] || type;
    },
    
    // 刷新数据
    refresh() {
      if (this.ipqcId) {
        this.fetchTestItems();
      } else {
        console.log('TestItemsList组件: 没有过程检验单ID，无法刷新检测项目');
      }
    },
    
    // 对外暴露的编辑方法
    edit(row) {
      this.handleEditTestItem(row);
    },
    
    // 对外暴露的查看方法
    view(row) {
      this.handleViewTestItem(row);
    },
    
    // 打开检测项选择器
    openTestItemSelector() {
      if (!this.templateId) {
        this.$message.warning('请先选择质检方案');
        return;
      }
      
      this.testItemSelectorVisible = true;
      this.selectorQueryParams.templateId = this.templateId;
      this.fetchTemplateItems();
    },
    
    // 获取模板关联的检测项列表
    async fetchTemplateItems() {
      this.selectorLoading = true;
      try {
        // 确保templateId是有效的
        const templateId = parseInt(this.templateId, 10);
        if (isNaN(templateId)) {
          this.$message.warning('质检方案ID无效');
          this.selectorLoading = false;
          return;
        }

        console.log('开始获取检测项列表，方案ID:', templateId);
        
        // 构建查询参数
        const params = {
          indexName: this.selectorQueryParams.indexName || undefined,
          indexCode: this.selectorQueryParams.indexCode || undefined,
          pageNum: this.selectorQueryParams.pageNum,
          pageSize: this.selectorQueryParams.pageSize
        };
        
        console.log('查询参数:', params);
        
        // 调用API方法
        const res = await selectQcTemplateIndexList(templateId, params);
        console.log('检测项API返回结果:', res);
        
        if (res && res.rows) {
          // 获取原始数据
          const rawData = res.rows;
          console.log('原始数据详情:', JSON.stringify(rawData));
          
          // 映射字段名 (将后端字段映射到前端表格使用的字段)
          this.templateItemsList = rawData.map(item => {
            // 打印每个项目的所有键名
            console.log('数据项的所有字段名:', Object.keys(item));
            
            // 创建一个新对象，确保所有需要的字段都存在
            return {
              // 尝试多种可能的字段名映射
              indexId: item.indexId || item.index_id,
              indexName: item.indexName || item.index_name,
              indexCode: item.indexCode || item.index_code,
              indexType: item.indexType || item.index_type,
              standerVal: item.standerVal || item.stander_val,
              thresholdMax: item.thresholdMax || item.threshold_max,
              thresholdMin: item.thresholdMin || item.threshold_min,
              unit: item.unit,
              qcTool: item.qcTool || item.qc_tool,
              checkMethod: item.checkMethod || item.check_method,
              crQuantityNum: item.crQuantityNum || item.cr_quantity_num,
              majQuantityNum: item.majQuantityNum || item.maj_quantity_num,
              minQuantityNum: item.minQuantityNum || item.min_quantity_num,
              attr1: item.attr1,
              attr2: item.attr2,
              attr3: item.attr3,
              attr4: item.attr4,
              
              // 保存原始数据，以便在选择时能获取所有字段
              _rawData: item
            };
          });
          
          this.selectorTotal = res.total;
          console.log('处理后的数据:', this.templateItemsList);
        } else if (res && res.data) {
          // 尝试其他可能的返回格式
          const rawData = res.data.rows || res.data;
          this.templateItemsList = rawData.map(item => {
            return {
              indexId: item.indexId || item.index_id,
              indexName: item.indexName || item.index_name,
              indexCode: item.indexCode || item.index_code,
              indexType: item.indexType || item.index_type,
              standerVal: item.standerVal || item.stander_val,
              thresholdMax: item.thresholdMax || item.threshold_max,
              thresholdMin: item.thresholdMin || item.threshold_min,
              unit: item.unit,
              qcTool: item.qcTool || item.qc_tool,
              checkMethod: item.checkMethod || item.check_method,
              crQuantityNum: item.crQuantityNum || item.cr_quantity_num,
              majQuantityNum: item.majQuantityNum || item.maj_quantity_num,
              minQuantityNum: item.minQuantityNum || item.min_quantity_num,
              attr1: item.attr1,
              attr2: item.attr2,
              attr3: item.attr3,
              attr4: item.attr4,
              _rawData: item
            };
          });
          this.selectorTotal = res.data.total || this.templateItemsList.length;
        } else {
          this.templateItemsList = [];
          this.selectorTotal = 0;
          console.log('未获取到检测项数据或返回格式不正确');
        }
      } catch (error) {
        console.error('获取检测方案关联检测项列表异常:', error);
        this.$message.error('获取检测项列表失败: ' + (error.message || '未知错误'));
        this.templateItemsList = [];
        this.selectorTotal = 0;
      } finally {
        this.selectorLoading = false;
      }
    },
    
    // 搜索模板检测项
    searchTemplateItems() {
      this.selectorQueryParams.pageNum = 1;
      this.fetchTemplateItems();
    },
    
    // 重置选择器查询条件
    resetSelectorQuery() {
      this.selectorQueryParams = {
        pageNum: 1,
        pageSize: 10,
        indexName: null,
        indexCode: null,
        templateId: this.templateId
      };
      this.fetchTemplateItems();
    },
    
    // 选择检测项
    selectTestItem(row) {
      console.log('选择的检测项数据:', row);
      
      // 获取原始数据（如果存在）
      const originalData = row._rawData || row;
      
      // 将选择的检测项数据回显到表单
      this.testItemForm.indexId = row.indexId;
      this.testItemForm.indexCode = row.indexCode;
      this.testItemForm.indexName = row.indexName;
      this.testItemForm.indexType = row.indexType;
      this.testItemForm.standerVal = row.standerVal;
      this.testItemForm.unit = row.unit;
      this.testItemForm.thresholdMax = row.thresholdMax;
      this.testItemForm.thresholdMin = row.thresholdMin;
      this.testItemForm.qcTool = row.qcTool;
      this.testItemForm.checkMethod = row.checkMethod;
      
      // 添加缺陷数量字段映射
      this.testItemForm.crQuantityNum = row.crQuantityNum;
      this.testItemForm.majQuantityNum = row.majQuantityNum;
      this.testItemForm.minQuantityNum = row.minQuantityNum;
      
      // 添加预留字段映射
      this.testItemForm.attr1 = row.attr1;
      this.testItemForm.attr2 = row.attr2;
      this.testItemForm.attr3 = row.attr3;
      this.testItemForm.attr4 = row.attr4;
      
      // 关闭选择器弹窗
      this.testItemSelectorVisible = false;
      this.$message.success('检测项选择成功');
    }
  }
};
</script>

<style scoped>
.test-items-container {
  padding: 10px 0;
}

.table-toolbar {
  margin-bottom: 10px;
  display: flex;
  justify-content: flex-start;
}

.table-toolbar .el-button {
  margin-right: 10px;
}

/* 空数据提示 */
.empty-data {
  padding: 30px 0;
  text-align: center;
}

.empty-tips {
  font-size: 14px;
  color: #909399;
  margin-top: 10px;
}

/* 表格内部样式 */
::v-deep .el-table {
  margin-bottom: 20px;
}

::v-deep .el-table th {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 500;
}

/* 添加表格行悬停样式 */
::v-deep .el-table tbody tr:hover {
  background-color: #f0f9ff !important;
  cursor: pointer;
}

/* 表格行点击效果 */
::v-deep .el-table tbody tr:active {
  background-color: #e6f2ff !important;
}

/* 表单样式 */
.el-input-number {
  width: 100%;
}

/* 检测项选择器样式 */
.input-with-select .el-input-group__append {
  background-color: #409EFF;
}

.input-with-select .el-input-group__append .el-button {
  color: #fff;
  border: none;
}

.selector-search {
  margin-bottom: 15px;
}

.empty-container {
  display: none;
}

/* 提示框样式 */
.tips-box {
  background-color: #f0f9eb;
  padding: 8px 16px;
  margin-bottom: 10px;
  border-radius: 4px;
  color: #67c23a;
  display: flex;
  align-items: center;
}

.tips-box i {
  margin-right: 8px;
}
</style> 